//
//  HTShareButton.swift
//  MagaCore
//
//  Created by MrMessy on 2023/5/25.
//

import SwiftUI

struct HTShareButton: View {

  @EnvironmentObject private var var_store: HTAppStore
  var var_shareIcon: String = "share"
  var var_onShare: () -> Void = {}
  var var_onDismiss: () -> Void = {}
  @State private var var_shareItems:[Any] = []
  @State private var var_isSharePresented: Bool = false

  var body: some View {
    ZStack {
      Button {
        var_onShare()
        var_shareItems.removeAll()
        var_shareItems.append(URL(string: var_store.state.var_shareState.var_share?.var_link ?? "") as Any)
        var_shareItems.append(var_store.state.var_shareState.var_share?.var_text ?? "")

        let av = UIActivityViewController(activityItems: var_shareItems, applicationActivities: nil)
        av.completionWithItemsHandler = { activityType, completed, returnedItems, error in
          var_onDismiss()
        }
        if UIDevice.current.userInterfaceIdiom == .pad {
          if let vc = UIApplication.shared.windows.first?.rootViewController {
            av.popoverPresentationController?.sourceView = vc.view
            av.popoverPresentationController?.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height, width: 0, height: 0)
            av.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.down
          }
        }
        av.modalPresentationStyle = .popover
        UIApplication.shared.windows.first?.rootViewController!.present(av, animated: true, completion: nil)
      } label: {
        Image(var_shareIcon)
          .resizable()
          .frame(width: 22, height: 22)
      }
    }.edgesIgnoringSafeArea(.all)
  }
}
